package com.fqj.myexcels.utils;

import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>@Title  标题</p>
 * <p>@Description  描述</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author Fu qingjian 作者</p>
 * <p>@date 2017/9/5 创建日期</p>
 * <p>fuqingjian@dgg.net 作者的公司邮箱</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
public class DataBaseMateTest {
    public static void main(String[] args) throws Exception {

        ResourceBundle bundle = ResourceBundle.getBundle("dggcoder");//读取application.properties文件，不加.properties后缀，不加路径名
        System.out.print(bundle.getString("dgg.coder.tablename"));//获取资源文件信息
        //1. JDBC连接MYSQL的代码很标准。
        Class.forName(bundle.getString("jdbc.datasource.driver-class-name")).newInstance();
        String url=bundle.getString("jdbc.datasource.url");
        String dbName=url.substring(url.lastIndexOf("/")+1,url.indexOf('?'));
        Connection conn = DriverManager.getConnection(bundle.getString("jdbc.datasource.url"),bundle.getString("jdbc.datasource.username"),bundle.getString("jdbc.datasource.password"));
        //2. 下面就是获取表的信息。
        DatabaseMetaData DBMetaData = conn.getMetaData();

        TableEntity tableEntity=new TableEntity();

        tableEntity.setDbName(dbName);
        //包前缀
        tableEntity.setPakagePre(bundle.getString("dgg.coder.pakagepre"));

        tableEntity.setEntityName(bundle.getString("dgg.coder.entityname"));

        ResultSet primaryKeyResultSet = DBMetaData.getPrimaryKeys(conn.getCatalog(),null,bundle.getString("dgg.coder.tablename"));
        while(primaryKeyResultSet.next()){
            String primaryKeyColumnName = primaryKeyResultSet.getString("COLUMN_NAME");
            tableEntity.setEntityKey(lineToHump(primaryKeyColumnName));
            tableEntity.setPrimaryKey(primaryKeyColumnName);
            System.out.println(primaryKeyColumnName);
        }


        /*通过getString("TABLE_NAME")，就可以获取表的名字了。
        从这里可以看出，前面通过getTables的接口的返回，JDBC是将其所有的结果，保存在一个类似table的内存结构中，而其中TABLE_NAME这个名字的字段就是每个表的名字。*/

        //4. 提取表内的字段的名字和类型
        String columnName;
        String columnType;
        ResultSet colRet = DBMetaData.getColumns(null,"%", bundle.getString("dgg.coder.tablename"),"%");

        tableEntity.setTableName(bundle.getString("dgg.coder.tablename"));
        List<ColumField> columFields=new ArrayList<>();
        StringBuffer allColumStr=new StringBuffer();
        while(colRet.next()) {
            columnName = colRet.getString("COLUMN_NAME");
            columnType = colRet.getString("TYPE_NAME");
            int datasize = colRet.getInt("COLUMN_SIZE");
            int digits = colRet.getInt("DECIMAL_DIGITS");
            int nullable = colRet.getInt("NULLABLE");
            ColumField columField=new ColumField();
            columField.setColumName(columnName);
            columField.setColumName_l(columnName.toLowerCase());
            columField.setFiledName(lineToHump(columnName));
            columField.setColumType(columnType);
            columFields.add(columField);

            allColumStr.append(columnName).append(",");
        }
        tableEntity.setAllClomnStr(allColumStr.substring(0,allColumStr.length()-1));

        tableEntity.setColumFields(columFields);


        FreeMarkerUtils freeMarkerUtils=FreeMarkerUtils.getInstance("/templates");
        Template t=freeMarkerUtils.getTemplate("dao.ftl");
//
        Map<String,Object> obj=new HashMap<>();
        try {
            obj.put("tableEntity",tableEntity);
            System.err.println(DataBaseMateTest.class.getResource("/").getPath());
            String codedesDir="codedes";
            String parenDir=DataBaseMateTest.class.getResource("/").getPath()+File.separator+codedesDir;
            File dir=new File(parenDir);
            if(!dir.exists()){
                dir.mkdirs();
            }
            FileOutputStream daofile=new FileOutputStream(parenDir+File.separator+tableEntity.getEntityName()+"Mapper.java");
            t.process(obj, new OutputStreamWriter(daofile)); // 往模板里写数据
//            t.process(obj, new OutputStreamWriter(System.err)); // 往模板里写数据

            Template t1=freeMarkerUtils.getTemplate("mapper.ftl");
            FileOutputStream mapperfile=new FileOutputStream(parenDir+File.separator+tableEntity.getEntityName()+"Mapper.xml");
            t1.process(obj, new OutputStreamWriter(mapperfile)); // 往模板里写数据
        } catch (Exception e) {
            e.printStackTrace();
        }



    }


    private static Pattern linePattern = Pattern.compile("_(\\w)");
    /**下划线转驼峰*/
    public static String lineToHump(String str){
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()){
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
